<template>
  <div
    class="search-box"
    :class="{ 'search-box--focused': isFocused }"
  >
    <!-- 搜索输入框 -->
    <div class="relative">
      <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
        <MagnifyingGlassIcon class="h-5 w-5 text-gray-400" />
      </div>
      
      <input
        ref="searchInput"
        v-model="searchQuery"
        type="text"
        :placeholder="placeholder"
        :disabled="disabled"
        class="search-input"
        @focus="handleFocus"
        @blur="handleBlur"
        @input="handleInput"
        @keydown.enter="handleSearch"
        @keydown.esc="handleEscape"
        @keydown.arrow-down="handleArrowDown"
        @keydown.arrow-up="handleArrowUp"
      >
      
      <!-- 清除按钮 -->
      <button
        v-if="searchQuery && !disabled"
        class="absolute inset-y-0 right-0 pr-3 flex items-center"
        type="button"
        @click="handleClear"
      >
        <XMarkIcon class="h-5 w-5 text-gray-400 hover:text-gray-600" />
      </button>
    </div>
    
    <!-- 搜索建议下拉框 -->
    <div
      v-if="showSuggestions && suggestions.length > 0"
      class="suggestions-dropdown"
    >
      <div
        v-for="(suggestion, index) in suggestions"
        :key="index"
        :class="[
          'suggestion-item',
          { 'suggestion-item--active': index === activeSuggestionIndex }
        ]"
        @click="handleSuggestionClick(suggestion)"
        @mouseenter="activeSuggestionIndex = index"
      >
        <MagnifyingGlassIcon class="h-4 w-4 text-gray-400 mr-2" />
        <span>{{ suggestion }}</span>
      </div>
    </div>
    
    <!-- 搜索历史 -->
    <div
      v-if="showHistory && searchHistory.length > 0 && !searchQuery"
      class="suggestions-dropdown"
    >
      <div class="px-3 py-2 text-xs font-medium text-gray-500 border-b">
        搜索历史
      </div>
      <div
        v-for="(historyItem, index) in searchHistory.slice(0, 5)"
        :key="index"
        :class="[
          'suggestion-item',
          { 'suggestion-item--active': index === activeSuggestionIndex }
        ]"
        @click="handleHistoryClick(historyItem)"
        @mouseenter="activeSuggestionIndex = index"
      >
        <ClockIcon class="h-4 w-4 text-gray-400 mr-2" />
        <span>{{ historyItem.query }}</span>
        <span class="ml-auto text-xs text-gray-400">
          {{ historyItem.result_count }} 条结果
        </span>
      </div>
    </div>
    
    <!-- 加载状态 -->
    <div
      v-if="loading"
      class="absolute inset-y-0 right-0 pr-3 flex items-center"
    >
      <LoadingSpinner size="small" />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
import { MagnifyingGlassIcon, XMarkIcon, ClockIcon } from '@heroicons/vue/24/outline'
import { useDebounce } from '@/composables/useDebounce'
import { articleService } from '@/services/articleService'
import { logger } from '@/utils/logger'
import LoadingSpinner from '@/components/common/LoadingSpinner.vue'

const props = defineProps({
  placeholder: {
    type: String,
    default: '搜索民法典条文...'
  },
  disabled: {
    type: Boolean,
    default: false
  },
  autoFocus: {
    type: Boolean,
    default: false
  },
  showSuggestions: {
    type: Boolean,
    default: true
  },
  showHistory: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['search', 'clear', 'focus', 'blur'])

// 响应式数据
const searchInput = ref(null)
const searchQuery = ref('')
const isFocused = ref(false)
const loading = ref(false)
const suggestions = ref([])
const searchHistory = ref([])
const activeSuggestionIndex = ref(-1)

// 计算属性
const showSuggestions = computed(() => {
  return props.showSuggestions && isFocused.value && suggestions.value.length > 0
})

const showHistory = computed(() => {
  return props.showHistory && isFocused.value && searchHistory.value.length > 0
})

// 防抖搜索建议
const debouncedGetSuggestions = useDebounce(async (query) => {
  if (!query || query.length < 1) {
    suggestions.value = []
    return
  }
  
  try {
    loading.value = true
    suggestions.value = await articleService.getSearchSuggestions(query)
  } catch (error) {
    logger.error('获取搜索建议失败:', error)
    suggestions.value = []
  } finally {
    loading.value = false
  }
}, 300)

// 事件处理
const handleFocus = () => {
  isFocused.value = true
  activeSuggestionIndex.value = -1
  emit('focus')
  
  // 获取搜索历史
  if (props.showHistory) {
    loadSearchHistory()
  }
}

const handleBlur = () => {
  // 延迟隐藏，允许点击建议
  setTimeout(() => {
    isFocused.value = false
    activeSuggestionIndex.value = -1
    emit('blur')
  }, 200)
}

const handleInput = () => {
  activeSuggestionIndex.value = -1
  
  if (props.showSuggestions) {
    debouncedGetSuggestions(searchQuery.value)
  }
}

const handleSearch = () => {
  const query = searchQuery.value.trim()
  if (query) {
    logger.userAction('执行搜索', { query })
    emit('search', query)
    isFocused.value = false
  }
}

const handleClear = () => {
  searchQuery.value = ''
  suggestions.value = []
  emit('clear')
  searchInput.value?.focus()
}

const handleEscape = () => {
  if (suggestions.value.length > 0) {
    suggestions.value = []
    activeSuggestionIndex.value = -1
  } else {
    searchInput.value?.blur()
  }
}

const handleArrowDown = (event) => {
  event.preventDefault()
  const maxIndex = Math.max(suggestions.value.length - 1, searchHistory.value.length - 1)
  if (activeSuggestionIndex.value < maxIndex) {
    activeSuggestionIndex.value++
  }
}

const handleArrowUp = (event) => {
  event.preventDefault()
  if (activeSuggestionIndex.value > 0) {
    activeSuggestionIndex.value--
  }
}

const handleSuggestionClick = (suggestion) => {
  searchQuery.value = suggestion
  handleSearch()
}

const handleHistoryClick = (historyItem) => {
  searchQuery.value = historyItem.query
  handleSearch()
}

// 加载搜索历史
const loadSearchHistory = async () => {
  try {
    searchHistory.value = await articleService.getSearchHistory()
  } catch (error) {
    logger.error('加载搜索历史失败:', error)
  }
}

// 监听搜索查询变化
watch(searchQuery, (newQuery) => {
  if (!newQuery) {
    suggestions.value = []
  }
})

// 生命周期
onMounted(() => {
  if (props.autoFocus) {
    searchInput.value?.focus()
  }
})

// 点击外部关闭建议
const handleClickOutside = (event) => {
  if (!event.target.closest('.search-box')) {
    isFocused.value = false
  }
}

onMounted(() => {
  document.addEventListener('click', handleClickOutside)
})

onUnmounted(() => {
  document.removeEventListener('click', handleClickOutside)
})

// 暴露方法
defineExpose({
  focus: () => searchInput.value?.focus(),
  clear: handleClear,
  search: handleSearch
})
</script>

<style scoped>
.search-box {
  @apply relative w-full;
}

.search-box--focused {
  @apply z-10;
}

.search-input {
  @apply w-full pl-10 pr-10 py-3 border border-gray-300 rounded-lg;
  @apply focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
  @apply disabled:bg-gray-50 disabled:text-gray-500 disabled:cursor-not-allowed;
  @apply text-base placeholder-gray-400;
}

.suggestions-dropdown {
  @apply absolute top-full left-0 right-0 mt-1;
  @apply bg-white border border-gray-200 rounded-lg shadow-lg;
  @apply max-h-64 overflow-y-auto z-50;
}

.suggestion-item {
  @apply flex items-center px-3 py-2 cursor-pointer;
  @apply hover:bg-gray-50 border-b border-gray-100 last:border-b-0;
}

.suggestion-item--active {
  @apply bg-blue-50 text-blue-700;
}

.suggestion-item:last-child {
  @apply border-b-0;
}

/* 响应式设计 */
@media (max-width: 640px) {
  .search-input {
    @apply text-base py-2.5;
  }
}
</style>
